package com.example.travel.interceptor;/*
 *#@Author : 林庆良
 *@simce : 2022/5/21
 *@file : AuthInterceptor.java
 #@Software : IntelliJ IDEA
*/


import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.travel.common.AuthAccess;
import com.example.travel.domain.entity.User;
import com.example.travel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //从请求头里面获取token
        System.out.println("拦截器");
        String token = request.getHeader("Authorization");

        //如果不是映射到方法，直接通过
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }else{
            HandlerMethod h = (HandlerMethod)handler;
            AuthAccess authAccess = h.getMethodAnnotation(AuthAccess.class);
            if(authAccess != null){
                return true;
            }
        }

        response.setContentType("text/plain;charset=utf8");

        if (StrUtil.isBlank(token)){
            response.getWriter().write("没有token");
            return false;
        }

        //获取token当中的用户userId
        String userId;
        try {
            //如果token有误。抛异常
            userId = JWT.decode(token).getAudience().get(0);
        }catch (Exception e){
            response.getWriter().write("token验证失败");
            return false;
        }

        User user = userService.getById(userId);
        if (user == null){
            response.getWriter().write("当前用户不存在");
            return false;
        }

        //用户密码加签验证token（验证token合法性）
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        }catch (Exception e){
            response.getWriter().write("token验证失败,请重新登录");
            return false;
        }
        return true;
    }
}
